<template>
  <el-row :gutter="6">
    <el-col :span="24" class="col-flex">
      <el-col class="breadcrumb-container">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/main' }">信息管理</el-breadcrumb-item>
          <el-breadcrumb-item>工程剪影</el-breadcrumb-item>
        </el-breadcrumb>
      </el-col>
      <el-col class="maincont-container">
        <div class="listview" v-if="listShow" v-loading="listloading">
          <div class="sketch-list-container">
            <div class="sketch-item" v-for="item in sketchDataList" :key="item.id">
              <el-image
                class="sketch-item-image"
                style="width:100%;height:100%"
                fit="contain"
                :src="getFirstUrl(item.url)"
                :preview-src-list="getUrlList(item.url)"
              ></el-image>
              <div v-if="true" class="self">
                <i class="el-icon-delete sketch-delete" @click="deleteData(item.id)"></i>
                <!-- <i class="el-icon-edit sketch-edit" @click="editData(item)"></i> -->
              </div>
              <div
                class="sketch-item-description"
              >{{'拍摄于'+item.si_date+' '+item.place+' 主要领导:'+item.leader}}</div>
            </div>

            <div title="添加工程剪影集" class="addbutton-con">
              <el-button @click="addNewProject" type="primary" icon="el-icon-circle-plus" circle></el-button>
            </div>
          </div>
        </div>
        <div
          class="data-form"
          v-if="!listShow"
          v-loading="loading"
          element-loading-text="正在提交......"
          element-loading-spinner="el-icon-loading"
        >
          <div>
            <h3>{{operationType}}</h3>
          </div>
          <el-form
            size="small"
            :model="sketchData"
            :rules="rules"
            ref="sketchData"
            label-width="100px"
          >
            <el-form-item label="项目名称">
              <el-input :readonly="true" v-model="sketchData.subject_id"></el-input>
            </el-form-item>
            <el-form-item label="拍摄时间" prop="si_date">
              <el-date-picker
                style="display:block;width:100%"
                type="date"
                v-model="sketchData.si_date"
                placeholder="选择拍摄日期"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="拍摄地点" prop="place">
              <el-input v-model="sketchData.place"></el-input>
            </el-form-item>
            <el-form-item label="主要领导" prop="leader">
              <el-input v-model="sketchData.leader"></el-input>
            </el-form-item>
            <el-form-item label="上传人">
              <el-input :readonly="true" v-model="sketchData.uploadby"></el-input>
            </el-form-item>
            <el-form-item label="上传日期">
              <el-input :readonly="true" v-model="sketchData.upload_time"></el-input>
            </el-form-item>
            <el-form-item label="照片列表">
              <div class="file-select">
                <el-upload
                  action="https://jsonplaceholder.typicode.com/posts/"
                  list-type="picture-card"
                  :file-list="fileList"
                  :accept="filetype"
                  :on-remove="handleRemove"
                  :before-remove="beforeRemove"
                  multiple
                  :before-upload="beforeUpload"
                  :http-request="uploadSectionFile"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
              </div>
            </el-form-item>
            <el-form-item style="text-align:right">
              <el-button type="primary" @click="submitForm('sketchData')">提交</el-button>
              <el-button @click="resetForm('sketchData')">取消</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-col>
  </el-row>
</template>

<script>
import { formatDate } from "@/utils/date";
import httpfile from "@/api/file/index";
import fileType from "@/config/file.type.config";

var glbVar = {};

export default {
  created() {
    glbVar.user = this.$store.state.m_user.userInfo;

    this.initList();
  },

  data() {
    return {
      filetype: fileType.sketch,

      operationType: "添加工程剪影",
      loading: false,
      listloading: false,
      sketchDataList: [],
      listShow: true,
      fileList: [], // 给上传组件的
      sketchData: {
        id: 0,
        subject_id: "",
        si_date: "",
        place: "",
        leader: "",
        uploadby: "",
        upload_time: "",
        url: ""
      },
      rules: {
        si_date: [
          { required: true, message: "请选择拍摄时间", trigger: "blur" }
        ],
        place: [{ required: true, message: "请输入拍摄地址", trigger: "blur" }],
        leader: [{ required: true, message: "请输入主要领导", trigger: "blur" }]
      },

      // 逻辑需要的
      fileList4api: []
    };
  },

  methods: {
    initList() {
      this.sketchDataList = [];
      this.$api.sketch
        .query(this.$store.state.projectInfo.projectName)
        .then(result => {
          if (result.code == 200) {
            this.sketchDataList = result.data;
            this.$message.success("加载成功");
          }
        })
        .catch(err => {
          console.log(err);
          this.$message.error(err);
        });
    },

    getFirstUrl(urls) {
      if (urls && urls !== "") {
        return urls.split(";")[0];
      } else {
        return null;
      }
    },

    getUrlList(urls) {
      if (urls && urls !== "") {
        return urls.split(";").filter(item => {
          return item.trim().length > 0;
        });
      } else {
        return [];
      }
    },

    /**
     * @description: 重置并返回
     * @param {type}
     * @return:
     */
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.fileList = [];
      this.fileList4api = [];
      this.listShow = true;
      this.isupdate = false;
    },

    /**
     * @description: 提交表单
     * @param {type}
     * @return:
     */
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.$confirm("提交后不可更改，是否继续？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(() => {
              this.sketchData.si_date = formatDate(
                this.sketchData.si_date,
                "yyyy-MM-dd hh:mm:ss"
              );
              this.loading = true;
              this.sketchData.url = this.fileList4api
                .map(item => {
                  return (
                    "/" +
                    this.$store.state.projectInfo.projectName +
                    "/工程剪影/" +
                    item.name
                  );
                })
                .join(";");
              if (this.isupdate) {
                this.$api.sketch
                  .update(this.sketchData)
                  .then(res => {
                    if (res.code == 200) {
                      this.$message.success("修改成功!");
                      this.listShow = !this.listShow;
                      this.initList();
                    }
                    this.loading = false;
                  })
                  .catch(err => {
                    this.loading = false;
                    this.$message.error("修改失败!!" + err);
                  });
              } else {
                this.$api.sketch
                  .add(this.sketchData)
                  .then(res => {
                    if (res.code == 200) {
                      this.$message.success("添加成功!");
                      this.listShow = !this.listShow;
                      this.initList();
                    }
                    this.loading = false;
                  })
                  .catch(err => {
                    this.loading = false;
                    this.$message.error("添加失败!!" + err);
                  });
              }
            })
            .catch(() => {
              return;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    /**
     * @description: 新增按钮
     * @param {type}
     * @return:
     */
    addNewProject() {
      this.sketchData = {
        id: 0,
        subject_id: "",
        si_date: "",
        place: "",
        leader: "",
        uploadby: "",
        upload_time: "",
        url: ""
      };
      this.listShow = !this.listShow;
      this.isupdate = false;
      this.operationType = "新增工程剪影";
      this.sketchData.uploadby = this.$store.state.m_user.userInfo.nick_name;
      this.sketchData.upload_time = formatDate(
        new Date(),
        "yyyy-MM-dd hh:mm:ss"
      );
      this.sketchData.subject_id = this.$store.state.projectInfo.projectName;
      this.fileList4api = [];
    },

    /**
     * @description: 编辑按钮
     * @param {type}
     * @return:
     */
    editData(item) {
      this.operationType = "编辑工程剪影";
      this.isupdate = true;
      this.listShow = false;
      this.sketchData = item;
      this.sketchData.si_date = new Date(this.sketchData.si_date);
      this.fileList = [];
      this.fileList4api = [];
      if (item.url != "") {
        item.url.split(";").forEach(ite => {
          if (ite != "") {
            let b = ite.split("/");
            this.fileList.push({
              name: b.slice(b.length - 1, b.length).toString(String),
              url: ite
            });
            this.fileList4api.push({
              name: b.slice(b.length - 1, b.length).toString(String),
              url:
                "/" +
                this.$store.state.projectInfo.projectName +
                "/工程剪影/" +
                b.slice(b.length - 1, b.length).toString(String)
            });
          }
        });
      }
    },

    /**
     * @description: 删除按钮
     * @param {type}
     * @return:
     */
    deleteData(id) {
      this.$confirm("此操作将永久删除该剪影集, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.listloading = true;
          this.$api.sketch
            .delete(id)
            .then(res => {
              if (res.code == 200) {
                this.listloading = false;
                this.$message.success("操作成功!");
                this.initList();
              } else {
                this.listloading = false;
                this.$message.success("删除失败:" + res.msg);
              }
            })
            .catch(err => {
              this.$message.success("操作失败!" + err);
            });
        })
        .catch(err => {});
    },

    //上传前检查格式
    beforeUpload(file) {
      let testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
      if (this.filetype.indexOf("." + testmsg.toLowerCase()) < 0) {
        this.$message({
          message: "上传文件格式不符合要求：" + testmsg,
          type: "warning"
        });
        return false;
      }
      return true;
    },
    /**
     * @description: 上传文件
     * @param {type}
     * @return:
     */
    uploadSectionFile(params) {
      const uid = params.file.uid;
      let keyname =
        formatDate(new Date(), "yyyyMMddhhmmss") +
        Math.floor(Math.random() * 1000);
      const fileData = new FormData();
      fileData.append("file", params.file);
      const query = {
        path:
          "/" +
          this.$store.state.projectInfo.projectName +
          "/工程剪影/" +
          keyname +
          params.file.name
      };

      const config = {
        headers: {
          "Content-Type": "multipart/form-data",
          token: window.sessionStorage.getItem("token")
        }
        // 这一段代码解决进度条不显示的问题，属于 axios 的使用知识。具体可以看文末的参考链接。
        // onUploadProgress: progressEvent => { 
        //   const percentCompleted = Math.floor(
        //     (progressEvent.loaded * 100) / progressEvent.total
        //   );
        //   params.onProgress({ percent: percentCompleted });
        // }
      };

      httpfile.upload(query, config, fileData).then(res => {
        if (res.status == 200) {
          this.fileList4api.push({
            url: query.path,
            name: keyname + params.file.name
          });
          params.onSuccess(res);
          console.log(this.fileList4api);

          // console.log("我是长度：" + this.fileList[index].length);
          // if (this.fileList[index].length > 3) {
          //   this.hideUpload[index] = true;
          //   console.log(this.hideUpload[index]);
          // }
        }
      });
    },

    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },

    handleRemove(file) {
      console.log(file);
      let temp = this.fileList.filter(item => {
        return item.uid != file.uid;
      });

      this.fileList4api = temp;
    }
  },

  computed: {
    companytypes() {
      if (user.user_type === "0") {
        return this.$store.state.m_user.roles;
      } else {
        return [{ roleName: user.nick_name, id: user.id }];
      }
    }
  }
};
</script>

<style lang="less" scoped>
.col-flex {
  padding-top: 30px;
  height: 100%;
  box-sizing: border-box;
  overflow: hidden;
  .breadcrumb-container {
    height: 30px;
    margin-top: -20px;
  }
  .maincont-container {
    height: calc(~"100% - 10px");
    margin-top: 3px;

    .listview {
      height: 100%;
      overflow: auto;
      text-align: center;
      .sketch-list-container {
        // display: flex;
        height: 100%;
        text-align: left;
        .sketch-item {
          height: 200px;
          width: 350px;
          position: relative;
          display: inline-block;
          margin: 10px;
          border-radius: 10px;
          .sketch-item-image {
            background-color: #aaaa;
            border-radius: 10px;
          }

          .self {
            display: none;
            position: absolute;
            top: 2px;
            right: 2px;
          }

          .sketch-edit {
            margin: 3px;
          }

          .sketch-delete {
            margin: 3px;
          }

          .sketch-item-description {
            box-sizing: border-box;
            width: 100%;
            text-align: left;
            position: absolute;
            left: 0px;
            bottom: 0px;
            padding: 5px;
            color: white;
            background-color: rgba(0, 0, 0, 0.5);
          }
        }

        .sketch-item:hover {
          .self {
            display: block;
          }
        }
      }

      /deep/.addbutton-con {
        button {
          box-shadow: 0px 0px 0px 3px #66b1ff55;
        }
        i {
          font-size: 20px;
        }
        z-index: 100;
        position: absolute;
        bottom: 10px;
        right: 10px;
        margin: 5px;
        height: 40px;
        border-radius: 50%;
        // box-shadow: 0px 0px 0px 2px gray;
      }
    }
    .data-form {
      padding: 0px 150px;
      height: 100%;
      overflow: auto;
      /deep/.file-select {
        text-align: left;
        .el-upload {
          width: 70px;
          height: 70px;
        }
        .el-upload--picture-card i {
          margin-top: 20px;
        }
        .el-upload--picture-card {
          line-height: 0%;
        }
        .el-upload-list--picture-card .el-upload-list__item {
          width: 70px;
          height: 70px;
          margin: 0;
        }
        .el-upload-list--picture-card
          .el-upload-list__item-actions
          span
          + span {
          margin: 0%;
        }
      }
    }
  }
}
</style>